#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
 
void *send_func();
void *recv_func();
 
int main(){
        int send_result, recv_result;
        int temp_result;
        pthread_t send_thread, recv_thread;
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        struct sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET; 
        serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  //IP
        serv_addr.sin_port = htons(5432);  //端口
        temp_result = connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
        if (temp_result == -1)
        {
                printf("Connection Fail\n");
                exit(1);
        } else {
                printf("---Connected---\n");
        }
 
        send_result = pthread_create(&send_thread, NULL, send_func, (void*)(long)sock);
        recv_result = pthread_create(&recv_thread, NULL, recv_func, (void*)(long)sock);

        if (recv_result != 0)
        {
                printf("recv_thread create failure\n");
                exit(1);
        }
        send_result = pthread_join(send_thread, NULL);
        recv_result = pthread_join(recv_thread, NULL);

 
        close(sock);
        return 0;
}

void *send_func(void *arg)
{
        int sockfd = (int)(long)arg;
        char send_buf[1024];
 
        while(1)
        {

                if (fgets(send_buf, 1024, stdin) == NULL)
                {
                        printf("no message\n");
                        continue;
                } else {
                        if(send(sockfd, send_buf, sizeof(send_buf), 0) == -1)
                        {
                                printf("send error\n");
                                continue;
                        } else {
                                printf("I : %s\n", send_buf);
                        }
                }
 
                if (strncmp(send_buf, "quit", 4) == 0)
                {
                        break;
                }
        }
        pthread_exit(0);
}

void *recv_func(void *arg)
{
        int sockfd = (int)(long)arg;
        char recv_buf[1024];
        while (1)
        {

                if (recv(sockfd, recv_buf, sizeof(recv_buf), 0) > 0)
                {
                        printf("You : %s\n", recv_buf);
                }
                if (strncmp(recv_buf, "quit", 4) == 0)
                {
                        break;
                }
        }
}

